﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using Newtonsoft.Json;

namespace MX.Core.Http.WebAction
{
	/// <summary>
	/// JSON类型表单
	/// </summary>
	public class JsonPostInfo : PostInfo
	{
		public object FormData { get; private set; }

		public JsonPostInfo (Dictionary<string, object> formData, string formEncoding)
			: base (PostContentType.Application_Json (), "utf-8")
		{
			FormData = formData;
		}

		public JsonPostInfo (NameValueCollection form)
			: base (PostContentType.Application_Json (), "utf-8")
		{
			var formData = new Dictionary<string, object> ();
			foreach (string key in form.Keys) {
				formData [key] = form [key];
			}
			FormData = formData;
		}


		public JsonPostInfo (object form)
			: base (PostContentType.Application_Json (), "utf-8")
		{
			FormData = form;
		}

		public JsonPostInfo (Dictionary<string, object> form)
			: this (form, "utf-8")
		{
		}

		public JsonPostInfo (string postString)
			: this (GetQueryParameter (postString, "utf-8", false), "utf-8")
		{

		}

		static protected Dictionary<string, object> GetQueryParameter (string url, string formEncoding, bool isEncoding)
		{
			Dictionary<string, object> pars = new Dictionary<string, object> ();
			var paraString = url.Substring (url.IndexOf ("?") + 1, url.Length - url.IndexOf ("?") - 1).Split ('&');
			for (int i = 0; i < paraString.Length; i++) {
				var nv = paraString [i].Split ('=');
				var name = nv [0];
				var value = nv [1];
				value = isEncoding ? UrlUnit.UrlEncode (value, Encoding.GetEncoding (formEncoding)) : value;
				pars.Add (name, value);
			}
			return pars;
		}

		public override string GetPostString ()
		{
			return  JsonConvert.SerializeObject (FormData, 
				Formatting.None, 
				new JsonSerializerSettings { 
					NullValueHandling = NullValueHandling.Ignore
				});
		}

		public override byte[] GetPostData ()
		{
			Encoding code = Encoding.GetEncoding (FormEncoding);
			return code.GetBytes (GetPostString ());
		}
	}
}
